﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TexasHoldem
{
    public class StraightFindingStrategy
    {
        const ushort AceValueInWheel = 1;

        public IEnumerable<Card> FindStraight(IEnumerable<Card> cards)
        {
            var straightOfValues = FindStraightIn(GetCardValuesForStraight(cards));
            if (straightOfValues == null)
                return null;
            return straightOfValues.Select(v => cards.First(c => v != AceValueInWheel ? c.Value == v : c.Face == CardFace.Ace));
        }

        IEnumerable<ushort> GetCardValuesForStraight(IEnumerable<Card> cards)
        {
            var allValues = cards.Select(c => c.Value);
            if (cards.Any(c => c.Face == CardFace.Ace))
                allValues = allValues.Union(new ushort[] { AceValueInWheel });

            return allValues;
        }

        IEnumerable<ushort> FindStraightIn(IEnumerable<ushort> sequence)
        {
            var straightCandidate = new List<ushort>();
            foreach (var next in sequence.Distinct().OrderByDescending(v => v)) {
                if (straightCandidate.Any() && next != straightCandidate.Last() - 1)
                    straightCandidate.Clear();
                straightCandidate.Add(next);

                if (straightCandidate.Count() >= 5)
                    return straightCandidate;
            }

            return null;
        }
    }
}
